const Constants = require('./constants')
const { URL } = require('./urls.js')
const 
{ HTTP } = require('./http.js')
const Log = require('./log.js')
const { formatToTime } = require('../utils/util.js')
var user = {
  // 是否已登录
  isLogin: false,
  headUrl:"",
  userName:"",
  userId: null,
  memberId: null,
  code:"",
  openid:"",
  token:null,
  gender:0 ,
  MemberLevel: 0, //会员等级
  expire: "",
  deviceId:"",//用户设备号，前端自己生成随机字符串
  userInfoReadyCallback:null,
  CouponCount:0,
  VideoEndTime:"",//会员到期时间
  HasVideoMember:false,//是否为视频会员
}


// 清空用户Cookie
var clearInfo = function() {
  try {
    wx.clearStorageSync()
    wx.removeStorageSync('user_token')
    user.isLogin=false;
    user.userId = null;
    user.token=null;
  } catch (e) {
    Log.error(e)
  }
}


const fetchUserInfo =  function(options) {

}

const saveUserInfo = function(res) {
  if(res==null||res==undefined){
    return;
  }
  console.log('userInfo')
  user.gender = res.Gender
  user.MemberLevel = res.MemberLevel
  user.userName = res.NickName
  user.headUrl=res.AvatarUrl
  user.userId = res.Id 
  user.memberId = res.MemberId
  user.CouponCount = res.CouponCount
  user.VideoEndTime = res.VideoEndTime
  user.HasVideoMember = res.HasVideoMember
  wx.setStorageSync('user_userName', res.NickName)
  wx.setStorageSync('user_headUrl', res.AvatarUrl)
  wx.setStorageSync('user_gender', res.Gender)
  wx.setStorageSync('user_vip', res.MemberLevel)
  wx.setStorageSync('user_id', res.Id)
  wx.setStorageSync('user_memberid', res.MemberId)
  wx.setStorageSync('CouponCount', res.CouponCount)
  wx.setStorageSync('VideoEndTime', res.VideoEndTime)
  wx.setStorageSync('HasVideoMember', res.HasVideoMember)
  if (user.userInfoReadyCallback) {
    console.log('app2');
    user.userInfoReadyCallback(res)
  }
}
const saveUserInfoNoJump = function (res) {
  if (res == null || res == undefined) {
    return;
  }
  console.log('userInfo')
  user.gender = res.Gender
  user.MemberLevel = res.MemberLevel
  user.userName = res.NickName
  user.headUrl = res.AvatarUrl
  user.userId = res.Id
  user.memberId = res.MemberId
  user.CouponCount = res.CouponCount
  user.VideoEndTime = res.VideoEndTime
  user.HasVideoMember = res.HasVideoMember
  wx.setStorageSync('user_userName', res.NickName)
  wx.setStorageSync('user_headUrl', res.AvatarUrl)
  wx.setStorageSync('user_gender', res.Gender)
  wx.setStorageSync('user_vip', res.MemberLevel)
  wx.setStorageSync('user_id', res.Id)
  wx.setStorageSync('user_memberid', res.MemberId)
  wx.setStorageSync('CouponCount', res.CouponCount)
  wx.setStorageSync('VideoEndTime', res.VideoEndTime)
  wx.setStorageSync('HasVideoMember', res.HasVideoMember)
}
const saveUserToken = function (res) {
  console.log('token')
  user.isLogin = true
  user.token = res.Token;
  // user.openid = res.openid;
  // user.userId = res.id
  // wx.setStorageSync('user_id', res.id)
  // wx.setStorageSync('openid', res.openid)
  var utoken = user.token
  wx.setStorageSync('user_token', utoken)

  // 获取用户信息
  getNetUserInfo();

}
const getUserInfo = function() {
  console.log('getuserInfo')
  if (!getIsLogin()) {
    return user;
  }
  user.isLogin = true
  user.openid = wx.getStorageSync('openid')
  user.userId = wx.getStorageSync('user_id')
  user.memberId = wx.getStorageSync('user_memberid')
  user.userName = wx.getStorageSync('user_userName')
  user.headUrl = wx.getStorageSync('user_headUrl')
  user.code = wx.getStorageSync('user_code')
  user.gender = wx.getStorageSync('user_gender')
  user.MemberLevel = wx.getStorageSync('user_vip')
  user.CouponCount = wx.getStorageSync('CouponCount')
  user.VideoEndTime = wx.getStorageSync('VideoEndTime')
  user.HasVideoMember = wx.getStorageSync('HasVideoMember')
  return user;
}
const getUserToken = function () {
  console.log('getuserToken')
  var utoken = wx.getStorageSync('user_token')
  return utoken;
}
const getIsLogin = function () {
  console.log('getIsLogin')
  var variable1=getUserToken();
  if (variable1 != null && variable1 != undefined && variable1 != ''&&variable1.length>0) {
    return true;
  } 
  return false;
}
const saveUserDeviceId = function () {
  console.log('saveUserDeviceId')
  user.deviceId = Math.random().toString(36).substr(8);
  wx.setStorageSync('user_deviceId', user.deviceId)
}
const getUserDeviceId = function () {
  console.log('getUserDeviceId')
  var variable1 = wx.getStorageSync('user_deviceId')
  if (variable1 != null && variable1 != undefined && variable1 != '' && variable1.length > 0) {
    return variable1;
  } else {
    saveUserDeviceId();
    return wx.getStorageSync('user_deviceId');
  }
}

const getNetUserInfo = function () {
  console.log('getNetUserInfo')
  HTTP({
    url: URL.user.postUserInfo,
    userToken: getUserToken(),
    data: {},
    showLoading: true,
    success: (res) => {
      //保存用户信息
      saveUserInfo(res.Data)
    },
    fail: (res) => {
      console.log(res)
    }
  })
}
//设置用户信息
const setUserInfoToNet = function () {
  /////获取用户微信信息
  wx.getUserInfo({
    success: function (res) {
      console.log("userInfo:" + res)
      //do anything
      ///重新登录
      wx.login({
        success: (resLogin) => {
          ///登录到来客集
          HTTP({
            url: URL.user.updateUser,
            data: {
              id: getUserInfo().userId,
              code: resLogin.code,
              nickName: res.userInfo.nickName,
              avatarUrl: res.userInfo.avatarUrl,
              gender: res.userInfo.gender,
              country: res.userInfo.country,
              province: res.userInfo.province,
              city: res.userInfo.city,
              language: res.userInfo.language,
            },
            showLoading: true,
            success: (ress) => {
              // 保存微信用户信息
              saveUserInfo(res.userInfo)
            },
            fail: (ress) => {
              console.log(ress)
            }
          })
        }
      });
      ///
    }
  })
            ////////用户登录到来客集结束
}
//授权登录
const sqLogin = function(){
//授权登录开始
  wx.login({
    success: (res) => {
      console.log('new code:' + res.code)
      // 将code传给服务端刷新session
      var code = res.code;
      if (code) {
        // 用户点击授权后，这里可以做一些登陆操作
        /////获取用户微信信息
        wx.getUserInfo({
          success: function (res) {
            console.log("userInfo:" + res)
            //do anything
            ///登录到来客集
            HTTP({
              url: URL.user.login,
              data: {
                AutoCode: code,
                // encryptedData: res.encryptedData,
                // iv: res.iv,
                NickName: res.userInfo.nickName,
                AvatarUrl: res.userInfo.avatarUrl,
                Gender: res.userInfo.gender,
                Country: res.userInfo.country,
                Province: res.userInfo.province,
                City: res.userInfo.city,
                Language: res.userInfo.language
              },
              showLoading: true,
              success: (res) => {
                //保存token
                saveUserToken(res.Data)
              },
              fail: (res) => {
                console.log(res)
                wx.showToast({
                  title: '服务器异常，请稍后再试',
                  icon: 'none'
                })
              }
            })
            ///
          }
        })
          ////////用户登录到来客集结束

      } else {
        console.log('获取用户登录失败：' + res.errMsg);
      }
    },
  })

//授权登录结束
}

//埋点接口相关
//埋点对象
var userLog = {
  transMode: "now",//传输模式：now:立即上传
  eventInfo: { 
    type: "",//事件类型：visit:访问 click:点击 share:分享
    starTime: Date.parse(new Date()),//事件开始时间(时间戳)
    endTime: ""//事件结束时间(时间戳)
    },
  userInfo: {
    accountId: getUserInfo().userId,
    openId: getUserInfo().openid,
    nickName: getUserInfo().userName
  },
  appInfo: {
    appName: "wxxcx",//app名称 wxxcx:微信小程序
    version: "1.0.0",//版本
    mode: "debug"//app数据模式 product：生产环境 debug：调试模式
  },
  deviceInfo:{
    deviceId: getUserDeviceId(),//设备号
    brand: wx.getSystemInfoSync().brand,//设备品牌
    model: wx.getSystemInfoSync().model,//设备型号
    language: wx.getSystemInfoSync().language,//语言
    system: wx.getSystemInfoSync().system,//操作系统及版本
    version: wx.getSystemInfoSync().version,//微信版本
    SDKVersion: wx.getSystemInfoSync().SDKVersion,//客户端基础库版本
    platform: wx.getSystemInfoSync().platform,//平台
    screenHeight: wx.getSystemInfoSync().screenHeight,
    screenWidth: wx.getSystemInfoSync().screenWidth,
    networkType:"",
    ip: "",
    latitude: "",
    longitude: "",
  },
  pageInfo: {
    currPage: "",//当前页面url
    prePage: "",//上一页页面url
  },
  elementInfo: {
    elementId: ""//元素ID
  },
  businessInfo: {
    productId: "",//商品id
    productType: "",//文章或者海报等
  }
}
//保存埋点信息
const saveNetUserLog = function (data) {
  console.log('saveNetUserLog')
  HTTP({
    url: URL.log.save,
    userToken: getUserToken(),
    data: data,
    showLoading: true,
    success: (res) => {
    },
    fail: (res) => {
      console.log(res)
    }
  })
}
//埋点相关内容结束

//外部接口
module.exports = {
  user: user,
  clearInfo: clearInfo,
  fetchUserInfo: fetchUserInfo,
  getUserInfo: getUserInfo,
  getUserToken: getUserToken, 
  getIsLogin: getIsLogin,
  getNetUserInfo: getNetUserInfo,
  setUserInfoToNet: setUserInfoToNet,
  getUserDeviceId: getUserDeviceId,
  userLog: userLog,
  saveNetUserLog: saveNetUserLog,
  sqLogin: sqLogin,
  saveUserInfoNoJump: saveUserInfoNoJump
}